package com.example.leo.mycharmingstudent.project.maintabfragment.subpagefragment.wxpublic;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.leo.mycharmingstudent.R;
import com.example.leo.mycharmingstudent.a0905.ToastUtil;
import com.example.leo.mycharmingstudent.project.constant.ApiInterface;
import com.example.leo.mycharmingstudent.project.maintabfragment.subpagefragment.adapter.ArticleListAdapter;
import com.example.leo.mycharmingstudent.project.maintabfragment.subpagefragment.entity.WXDataEntity;
import com.example.leo.mycharmingstudent.project.util.OkHttpUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;

/**
 * Created by Leo on 2020/10/18.
 */

public class PublicDetailFragment extends Fragment {

    public static final String ID = "id";
    public static final String NAME = "name";

    SmartRefreshLayout mRefreshLayout;
    RecyclerView mRecyclerView;
    EditText mSearchEdit;
    TextView mTintTv;
    TextView mSearchTv;

    private int id;
    private int mCurrentPage = 1;
    private ArticleListAdapter mAdapter;
    private boolean isRefresh = true;
    private int articlePosition;
    private String mAuthor;
    private String tint;
    private boolean isSearchStatus;
    private String searchString;

    public static PublicDetailFragment newInstance(int param1, String param2) {
        PublicDetailFragment fragment = new PublicDetailFragment();
        Bundle args = new Bundle();
        args.putInt(ID, param1);
        args.putString(NAME, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_public_detail, container, false);

        mSearchEdit = inflate.findViewById(R.id.search_edit);
        mTintTv = inflate.findViewById(R.id.search_tint_tv);
        mSearchTv = inflate.findViewById(R.id.search_tv);

        mRefreshLayout = inflate.findViewById(R.id.srl_fragment_public_detail);
        mRecyclerView = inflate.findViewById(R.id.we_detail_list_recycler_view);
        return inflate;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initRecyclerView();
        setRefresh();
        Bundle bundle = getArguments();
        id = bundle.getInt(ID, 0);
        if (id == 0) {
            return;
        }
        mAuthor = bundle.getString(NAME, "");
        initTitle();

        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(mSearchEdit.getText().toString())) {
                    mTintTv.setText(tint);
                } else {
                    mTintTv.setText("");
                }
            }
        });

        mSearchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isSearchStatus = true;
                isRefresh = true;
                mCurrentPage = 1;
                searchString = mSearchEdit.getText().toString();
                getWxSearchSumData(id, mCurrentPage, mSearchEdit.getText().toString());
            }
        });

        //重置当前页数，防止页面切换后当前页数为较大而加载后面的数据或没有数据
        mCurrentPage = 1;
        getWxDetailData(id, mCurrentPage);
    }

    private void initRecyclerView() {
        mAdapter = new ArticleListAdapter(R.layout.item_activity_sub_page, null);
        //添加条目点击事件
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mAdapter.getData().size() <= 0 || mAdapter.getData().size() <= position) {
                    return;
                }
                // to do something 做一些事情
            }
        });
        //添加条目单个控件点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {

                }
            }
        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setRefresh() {
        mRefreshLayout.setPrimaryColorsId(R.color.colorPrimary, R.color.white);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage = 1;
                if (id != 0) {
                    isRefresh = true;
                    getWxDetailData(id, 0);
                }
                refreshLayout.finishRefresh(1000);
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage++;
                if (id != 0) {
                    isRefresh = false;
                    if (isSearchStatus) {
                        getWxSearchSumData(id, mCurrentPage, searchString);
                    } else {
                        getWxDetailData(id, mCurrentPage);
                    }
                }
                refreshLayout.finishLoadMore(1000);
            }
        });
    }

    private void initTitle() {
        tint = mAuthor + "带你" + getString(R.string.search_tint);
        mTintTv.setText(tint);
    }

    private void getWxSearchSumData(int id, int currentPage, String key) {
        String url = String.format(Locale.CHINA, ApiInterface.WX_SEARCH_SUM_DATA, id, currentPage, key);
        OkHttpUtil.enqueue(url, new OkHttpUtil.MainThreadCallBack() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String result) {
                Gson gson = new Gson();
                WXDataEntity wxDataEntity = gson.fromJson(result, WXDataEntity.class);
                if (wxDataEntity.getErrorCode() == 0) {
                    WXDataEntity.DataBean wxSearchData = wxDataEntity.getData();
                    if (isRefresh) {
                        mAdapter.replaceData(wxSearchData.getDatas());
                    } else {
                        if (wxSearchData.getDatas().size() > 0) {
                            mAdapter.addData(wxSearchData.getDatas());
                        } else {
                            ToastUtil.showToast(getContext(), getString(R.string.load_more_no_data));
                        }
                    }
                }
            }
        });
    }

    private void getWxDetailData(int id, int currentPage) {
        String url = String.format(Locale.CHINA, ApiInterface.WX_SUM_DATA, id, currentPage);
        OkHttpUtil.enqueue(url, new OkHttpUtil.MainThreadCallBack() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String result) {
                Gson gson = new Gson();
                WXDataEntity wxDataEntity = gson.fromJson(result, WXDataEntity.class);
                if (wxDataEntity.getErrorCode() == 0) {
                    WXDataEntity.DataBean wxSumData = wxDataEntity.getData();
                    if (isRefresh) {
                        mAdapter.replaceData(wxSumData.getDatas());
                    } else {
                        if (wxSumData.getDatas().size() > 0) {
                            mAdapter.addData(wxSumData.getDatas());
                        } else {
                            ToastUtil.showToast(getContext(), getString(R.string.load_more_no_data));
                        }
                    }
                }
            }
        });
    }

}
